package top.chenfu1201.clientApi.config;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.chenfu1201.clientApi.exception.GlobalException;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler
    public Map<String, Object> exceptionHandler(Exception e) {
        GlobalException exception;
        if (e instanceof GlobalException) {
            exception = (GlobalException) e;
        } else {
            exception = GlobalException.defaultFail();
        }
        return response(exception);
    }

    public Map<String, Object> response(GlobalException e) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", e.getCode());
        map.put("msg", e.getMsg());
        map.put("data", e.getData());
        log.info(JSON.toJSONString(map));
        return map;
    }

}
